<?php
namespace App\Models;
use App\Constants\ErrorResponse;
use App\Filters\QueryFilter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
 * Copyright (C), 2021-2021, old_liu_cms.
 * FileName: Category.php
 * Description: 说明
 *
 * @author old_liu_cms
 * @Create Date    2021/10/10 16:27
 * @Update Date    2021/10/10 16:27 By old_liu_cms
 * @version v1.0
 */

class Category extends Model {
//    use SoftDeletes;
    protected $fillable = ['title','href'];

    public function scopeFilter($query, QueryFilter $filters)
    {
        return $filters->apply($query);
    }

    /**
     * FunctionName：getAll
     * Description：
     * Author：old_liu_cms
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getAll()
    {
       return self::query()->get();
    }

    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    /**
     * FunctionName：store
     * Description：创建
     * Author：lwl
     * @param array $params
     * @return null
     */
    public static function store(array $params)
    {
        if (!self::query()->create($params)) {
            errorHttpResponse(ErrorResponse::ERROR_OPERATION_FAIL);
        }
        return null;
    }

    /**
     * FunctionName：lists
     * Description：
     * Author：old_liu_cms
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function lists($filter)
    {
        return self::query()->filter($filter)->with('posts')->paginate(20);
    }

    /**
     * FunctionName：show
     * Description：详情
     * Author：lwl
     * @param int $id
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function show(int $id)
    {
        if (!$result = self::query()->whereKey($id)->first()) {
            errorHttpResponse(ErrorResponse::ERROR_DATA_NOT_EXISTS);
        }
        return $result;
    }

    /**
     * FunctionName：edit
     * Description：更新
     * Author：lwl
     * @param array $params
     * @return int
     */
    public static function edit(array $params)
    {
        $result = self::detail($params['id']);
        if (!$result->update($params)) {
            errorHttpResponse(ErrorResponse::ERROR_OPERATION_FAIL);
        }
        return null;
    }

    /**
     * FunctionName：remove
     * Description：删除
     * Author：lwl
     * @param int $id
     * @return null
     */
    public static function remove(int $id)
    {
        $result = self::show($id);
        if (!$result->delete($id)) {
            errorHttpResponse(ErrorResponse::ERROR_OPERATION_FAIL);
        }
        return null;
    }
}
